# ex_huanglx3
# 2021/12/21 15:51
# PyCharm
from api.login_api.v1_login import v1_login
import pytest
import requests
import time
import json

def pytest_addoption(parser):
    #添加参数到.ini配置文件
    parser.addini("base_url",type=None,default="http://49.235.92.12:8200",help="默认地址")
    parser.addini("shop_url",type=None,default="http://49.235.92.12:7005",help="商城地址")

@pytest.fixture(scope="session")
def base_url(pytestconfig):
    #获取.ini配置文件参数
    url = pytestconfig.getini("base_url")
    return url

@pytest.fixture(scope="session")
def shop_url(pytestconfig):
    #获取.ini配置文件shop地址
    url = pytestconfig.getini("shop_url")
    return url

@pytest.fixture(scope="session")
def session(pytestconfig):
    session = requests.Session()
    base_url = pytestconfig.getini("shop_url")
    v1_login(session=session,base_url=base_url)
    return session

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    '''收集测试结果'''
    # print(terminalreporter.stats)
    total = terminalreporter._numcollected
    passed= len([i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown'])
    failed=len([i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown'])
    error=len([i for i in terminalreporter.stats.get('error', []) if i.when != 'teardown'])
    skipped=len([i for i in terminalreporter.stats.get('skipped', []) if i.when != 'teardown'])
    successful = len(terminalreporter.stats.get('passed', []))/terminalreporter._numcollected*100
    # terminalreporter._sessionstarttime 会话开始时间
    duration = time.time() - terminalreporter._sessionstarttime
    print('total times: %.2f' % duration, 'seconds')

    result_json = {
  "TOTAL": total,
  "PASSED": passed,
  "FAILED": failed,
  "ERROR": error,
  "SKIPPED": skipped,
  "SUCCESSFUL": "%.2f%%" %successful,
  "TOTAL_TIMES": "%.2fs" %duration
}
    with open("result.json", "w") as fp:
        # fp.write("TOTAL=%s" % total+"\n")
        # fp.write("PASSED=%s" % passed+"\n")
        # fp.write("FAILED=%s" % failed+"\n")
        # fp.write("ERROR=%s" % error+"\n")
        # fp.write("SKIPPED=%s" % skipped+"\n")
        # fp.write("SUCCESSFUL=%.2f%%" % successful+"\n")
        # fp.write("TOTAL_TIMES=%.2fs" % duration)
        json.dump(result_json,fp)
        print("加载入文件完成...")

@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    print('------------------------------------')

    # 获取钩子方法的调用结果
    out = yield
    print('用例执行结果', out)

    # 3. 从钩子方法的调用结果中获取测试报告
    report = out.get_result()

    print('测试报告：%s' % report)
    print('步骤：%s' % report.when)
    print('nodeid：%s' % report.nodeid)
    print('description:%s' % str(item.function.__doc__))
    print(('运行结果: %s' % report.outcome))